﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SmartSpace.UI.Silverlight;

namespace DynamicChart.UI
{
    public partial class ChartView : AppView
    {
        private string _module;
        private DynamicChart.UI.ServiceRef.DateRange _dateRange;
        private int _curYear;
        private List<FrameworkElement> _chartParts;
        private string _argumentString;

        public ChartView()
            :base (new Guid("{72DBBBF4-2FAE-4768-A20A-DB57D22D512D}"), "chart view")
        {
            InitializeComponent();

            _chartParts = new List<FrameworkElement>();
        }

        internal ChartView(string module)
            : this()
        {
            _module = module;
        }

        internal ChartView(string module, DynamicChart.UI.ServiceRef.DateRange dateRange)
            : this(module)
        {
            _dateRange = dateRange;
        }

        public override string GetCaption()
        {
            return _curYear.ToString();
        }

        protected override void OnExtendShown()
        {
            if (IsFirstDisplay)
            {
                if (string.IsNullOrEmpty(_module))
                {
                    _module = this.Arguments["module"].ToString();
                }

                foreach (var key in this.Arguments.Keys)
                {
                    _argumentString += string.Format("{0}={1},", key, this.Arguments[key]);
                }

                this._ctlDateSlider.DateRangeChanged += new Action<string, DateTime>(_ctlDateSlider_DateRangeChanged);
                this._ctlDateSlider.Enter += new Action<DynamicChart.UI.ServiceRef.DateRange>(_ctlDateSlider_Enter);

                LoadPackage();
            }

            base.OnExtendShown();
        }

        private void LoadPackage()
        {
            List<DynamicChart.UI.ServiceRef.ChartDefinition> chartDefs = new List<ServiceRef.ChartDefinition>();

            ServiceRef.ChartDefinition chartDef = new ServiceRef.ChartDefinition();
            chartDef.Row = 0;
            chartDef.Col = 0;
            chartDef.RowSpan = 1;
            chartDef.ColSpan = 1;
            chartDef.Module = _module;
            chartDef.DateRange = new ServiceRef.DateRange();
            chartDef.DateRange.Mode = "y";
            chartDef.DateRange.BeginDate = DateTime.Now.AddYears(-5);
            chartDef.DateRange.CurrentDate = DateTime.Now;
            chartDef.DateRange.EndDate = DateTime.Now.AddYears(5);
            chartDefs.Add(chartDef);

            _chartParts.Clear();

            #region 生成布局Grid
            _ctlPanel.RowDefinitions.Clear();
            _ctlPanel.ColumnDefinitions.Clear();
            _ctlPanel.Children.Clear();

            Grid container = _ctlPanel;

            int rowCount = 0;
            int colCount = 0;
            foreach (var itemDef in chartDefs)
            {
                if (itemDef.Row >= rowCount)
                {
                    rowCount += (itemDef.Row - rowCount) + 1;
                }

                if (itemDef.Col >= colCount)
                {
                    colCount += (itemDef.Col - colCount) + 1;
                }
            }

            for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
            {
                RowDefinition rowDef = new RowDefinition();
                container.RowDefinitions.Add(rowDef);
            }

            for (int colIndex = 0; colIndex < colCount; colIndex++)
            {
                ColumnDefinition colDef = new ColumnDefinition();
                container.ColumnDefinitions.Add(colDef);
            }
            #endregion

            #region 创建图表
            DynamicChart.UI.ServiceRef.ChartDefinition item = chartDefs[0];

            FrameworkElement part = null;

            if (item.IsPackage)
            {
                part = new DynamicChart.UI.ChartPartDecorator();

                (part as DynamicChart.UI.ChartPartDecorator).Enter += new EventHandler(part_Enter);
            }
            else
            {
                part = new DynamicChart.UI.ChartPart();
            }

            part.Tag = item;

            part.Margin = new Thickness(5, 5, 0, 0);
            container.Children.Add(part);
            Grid.SetRow(part, item.Row);
            Grid.SetColumn(part, item.Col);
            Grid.SetRowSpan(part, item.RowSpan);
            Grid.SetColumnSpan(part, item.ColSpan);

            _chartParts.Add(part);

            #endregion

            #region 初始化时间条 - 触发时间变更，加载数据
            if (item.DateRange == null || !item.DateRange.IsVisible)
            {
                _ctlDateSlider.SetDateRange(item.DateRange);
                _ctlDateSlider.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                _ctlDateSlider.SetDateRange(item.DateRange);
                _ctlDateSlider.Visibility = System.Windows.Visibility.Visible;
            }
            #endregion
        }

        private void LoadChartDatas()
        {
            foreach (var item in _chartParts)
            {
                (item as IChartPart).IsBusy();

                DynamicChart.UI.ServiceRef.ChartDefinition chartDef = item.Tag as DynamicChart.UI.ServiceRef.ChartDefinition;
                if (_ctlDateSlider.DateRange.IsVisible)
                {
                    chartDef.DateRange = _ctlDateSlider.DateRange;
                }

                DynamicChart.UI.ServiceRef.DynamicChartWebServiceSoapClient client = DynamicChartModule.CreateProxy();
                client.GetDataCompleted += new EventHandler<DynamicChart.UI.ServiceRef.GetDataCompletedEventArgs>(client_GetDataCompleted);
                client.GetDataAsync(chartDef.Module, chartDef.DateRange, _argumentString, item);
            }
        }

        void client_GetDataCompleted(object sender, DynamicChart.UI.ServiceRef.GetDataCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.IsSuccess)
                {
                    //DynamicChart.ChartPart part = e.UserState as DynamicChart.ChartPart;
                    DynamicChart.UI.IChartPart part = e.UserState as DynamicChart.UI.IChartPart;

                    part.SetChartData(e.Result.Data);
                }
                else
                {
                    MessageBox.Show(e.Result.Message);
                }
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
        }

        void _ctlDateSlider_DateRangeChanged(string mode, DateTime currentDate)
        {
            LoadChartDatas();
        }

        void _ctlDateSlider_Enter(DynamicChart.UI.ServiceRef.DateRange dateRange)
        {
            //this.SwitchView(new ChartPackageView(_module, dateRange));
        }

        void part_Enter(object sender, EventArgs e)
        {
            FrameworkElement part = sender as FrameworkElement;
            DynamicChart.UI.ServiceRef.ChartDefinition chartDefinition = part.Tag as DynamicChart.UI.ServiceRef.ChartDefinition;
            this.SwitchView(new ChartPackageView(chartDefinition.Module, _ctlDateSlider.DateRange));
        }
    }
}
